package com.testDemo.utils;

import cn.hutool.core.io.FileUtil;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.model.enums.CompressionLevel;
import net.lingala.zip4j.model.enums.EncryptionMethod;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author: zour
 * @date: 2024/1/10
 * @description:
 */
public class ZipFileSplitter {


    /**
     * 分卷压缩
     *
     * @param srcFiles  要压缩的文件绝对路径列表(支持多个文件的合并压缩)
     * @param destFile     要压缩的zip文件名
     * @param passwd    压缩密码
     * @param fileSize 分卷大小
     * @return 压缩文件路径 如分卷会返回以 ,” 分隔的文件路径列表
     */
    public static String zip(List<File> srcFiles, String destFile, String passwd, long fileSize) throws ZipException {
        String zipFiles = null;
        File tmpFile = new File(destFile);
        if (tmpFile.exists()) {
            tmpFile.delete();
        }

        ZipFile zipFile = new ZipFile(destFile, passwd.toCharArray());

        if (srcFiles != null && srcFiles.size() > 0) {
            ZipParameters parameters = new ZipParameters();
            if (!StringUtils.isBlank(passwd)) {
                parameters.setEncryptFiles(true);
                parameters.setCompressionLevel(CompressionLevel.MAXIMUM);
                parameters.setEncryptionMethod(EncryptionMethod.AES);
            }
            //未指定则设置为512KB
            if (fileSize == 0) {
                fileSize = 512*1024;
            }
            int len = srcFiles.size();
            File emp = null;
            for (int i = 0; i < len; i++) {
                emp = srcFiles.get(i);
                FileUtil.copy(emp,new File("c:/temp/dict/"+ emp.getName()),true);
            }
            zipFile.createSplitZipFileFromFolder(new File("c:/temp/dict"), parameters, true, fileSize);

//            zipFile.createSplitZipFile(srcFiles, parameters, true, fileSize);

        }
        return zipFiles;
    }

    public static void main(String[] args) throws IOException {
        List<File> filesToCompress = new ArrayList<>(); // 要压缩的文件列表

        // 添加需要压缩的文件路径到filesToCompress列表中
        filesToCompress.add(new File("C:\\temp\\1017HKMCA-AAS-NFSD-Batch3.docx"));
        filesToCompress.add(new File("C:\\temp\\2024010816.csv"));

        String zipFileName = "test"; // 最终生成的ZIP文件名称
        int maxSizePerPartition = 3 * 1024 * 1024; // 单个ZIP文件的最大大小（字节）
        zip(filesToCompress,"C:\\temp\\test.zip","1",0);

    }
}